class DeviceTool {
	constructor() {
		this.micDevices = [];
		this.speakerDevices = [];
		this.videoDevices = [];
		this.allMediaDevices = [];
		this.init();
	}

	async init() {
		await this.getUserDevicesEnum();
		this.addUserDeviceUpdate();
	}

	async getUserDevicesEnum() {
		try {
			const userDevices = await navigator.mediaDevices.enumerateDevices();
			this.setAllMediaDevices(userDevices);
		} catch (err) {
			console.error('get user devices failed');
		}
	}

	/** 设置麦克风设备列表 */
	setMicDevices() {
		this.micDevices = this.getAllMediaDevices()
			.filter(device => device.kind === 'audioinput')
			.map(device => ({ id: device.id, label: device.label, groupId: device.groupId }));
	}

	/** 获取麦克风设备列表 */
	getMicDevices() {
		return this.micDevices;
	}

	/** 设置扬声器设备列表 */
	setSpeakerDevices() {
		this.speakerDevices = this.getAllMediaDevices()
			.filter(devices => devices.kind === 'audiooutput')
			.map(device => ({ id: device.id, label: device.label, groupId: device.groupId }));
	}
	/**获取扬声器设备列表 */
	getSpeakerDevices() {
		return this.speakerDevices;
	}

	/** 设置视频设备列表 */
	setVideoDevices() {
		this.videoDevices = this.getAllMediaDevices()
			.filter(device => device.kind === 'videoinput')
			.map(device => ({ id: device.id, label: device.label, groupId: device.groupId }));
	}

	/** 获取视频设别列表 */
	getVideoDevices() {
		return this.videoDevices;
	}

	/** 设置所有媒体设备 */
	async setAllMediaDevices(devices) {
		const result = devices.map(device => ({ id: device.deviceId, label: device.label, kind: device.kind, groupId: device.groupId }));
		this.allMediaDevices = result;
		this.setMicDevices();
		this.setSpeakerDevices();
		this.setVideoDevices();
	}

	/** 获取所有列表枚举值 */
	getAllMediaDevices() {
		return this.allMediaDevices;
	}

	/** 监听设备列表发生变化事件 */
	addUserDeviceUpdate() {
		if (navigator.mediaDevices || window.navigator.mediaDevices) {
			navigator.mediaDevices.addEventListener('devicechange', async event => {
				const result = await event.target.enumerateDevices();
				const allDevices = result.map(device => ({ id: device.deviceId, label: device.label, kind: device.kind, groupId: device.groupId }));
				this.getDeviceChange(allDevices);
			});
		}
	}

	/** 设备列表发生变化 */
	getDeviceChange(devices) {
		const allDeivices = this.getAllMediaDevices();
		this.getDiffKey(allDeivices, devices);
		this.getUserDevicesEnum();
	}

	/** 求差值 */
	getDiffKey(allArr, partArr) {
		let temp = [];
		let result = { type: 'remove', devices: [] };
		if (allArr.length < partArr.length) {
			temp = partArr;
			partArr = allArr;
			allArr = temp;
			result.type = 'add';
		}
		for (let i = allArr.length - 1; i >= 0; i--) {
			let flag = false;
			for (let j = 0; j < partArr.length; j++) {
				if (allArr[i].label === partArr[j].label) {
					flag = true;
				}
			}
			if (!flag) {
				if (allArr[i].id !== 'communications' && allArr[i].id !== 'default') {
					console.log(allArr[i].id);
					result.devices.push(allArr[i]);
				}
			}
		}

		return result;
	}

	/** 根据属性去重 */
	arrUnique(arr, key) {
		for (let i = 0; i < arr.length; i++) {
			for (let j = i + 1; j < arr.length; j++) {
				if (arr[i][key] == arr[j][key]) {
					arr.splice(j, 1);
					j--;
				}
			}
		}
		return arr;
	}

	/**
	 * 获取用户设备信息
	 * @returns { String } 用户设备信息
	 */
	getUserPhone() {
		if (window.navigator.userAgent) {
			let ua = window.navigator.userAgent.toLocaleLowerCase();
			let webview = ua.match(/MicroMessenger/i) == 'micromessenger';
			let android = ua.match(/Android/i) == 'android' || ua.match(/Linux/i) == 'linux';
			let iphone = ua.match(/iPhone/i) == 'iphone' || ua.match(/IOS/i) == 'ios';
			if (webview && !iphone) {
				return 'Webview';
			} else if (android && !webview) {
				return 'Android';
			} else if (iphone) {
				return 'IOS';
			} else {
				return 'PC';
			}
		}
	}

	/**
	 *
	 * @param { Array } devices 设备列表数组
	 * @returns { Array } 有效设备列表
	 */
	filterAndroidCameraLabel(devices) {
		// 有效设备
		let activeDevice = [];
		for (let i = 0; i < devices.length; i++) {
			let label = devices[i].label;
			// 查找 camera 标签的前后标识,手机处理方式
			if (label.indexOf('front') !== -1 || label.indexOf('Front') !== -1 || label.indexOf('back') !== -1 || label.indexOf('Back') !== -1) {
				// 默认手机 camera2 0 代表默认后置摄像头
				if (devices[i].label.indexOf('camera2 0') != -1 || devices[i].label.indexOf('camera2 1') != -1) {
					activeDevice.push(devices[i]);
				}
				// 电脑摄像头
			} else {
				activeDevice.push(devices[i]);
			}
		}
		return activeDevice;
	}

	/**
	 * 停止当前视频流
	 * @param { Object } stream
	 * @returns { Object }  视频流
	 */
	stopStream(stream) {
		if (!stream) {
			return;
		}
		if (stream.mediaStream) {
			let oldVideoTracks = stream.mediaStream.getVideoTracks();
			let oldAudioTracks = stream.mediaStream.getAudioTracks();
			for (let track of oldVideoTracks) {
				track.stop();
			}
			for (let track of oldAudioTracks) {
				track.stop();
			}
		} else {
			let oldVideoTracks = stream.getVideoTracks();
			let oldAudioTracks = stream.getAudioTracks();
			for (let track of oldVideoTracks) {
				track.stop();
			}
			for (let track of oldAudioTracks) {
				track.stop();
			}
		}
	}
}

export { DeviceTool };
